package unionFind;

import java.util.HashSet;
import java.util.Set;

/**
 * 765. 情侣牵手
 */
public class P765 {
    public int minSwapsCouples(int[] row) {
        //1. 初始化
        int[] union = new int[row.length / 2];
        for (int i = 0; i < union.length; i++)
            union[i] = i;
        //2. 赋值
        for (int i = 0; i < row.length; i += 2) {
            int x = row[i];
            int y = row[i + 1];
            if (x / 2 != y / 2) {//不是同一家的
                union(union, x / 2, y / 2);
            }
        }
        Set<Integer> unique = new HashSet<>();
        for (int i = 0; i < union.length; i++) {
            unique.add(find_parent(union, i));
        }
        return union.length - unique.size();
    }

    private void union(int[] union, int x, int y) {
        int x_p = find_parent(union, x);
        int y_p = find_parent(union, y);
        union[y_p] = x_p;
    }

    private int find_parent(int[] union, int pos) {
        return union[pos] == pos ? pos : find_parent(union, union[pos]);
    }

    public static void main(String[] args) {
        int[] row = {3, 2, 0, 1};
        int i = new P765().minSwapsCouples(row);
        System.out.println(i);
    }
}
